<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model.trim="query.code" class="filter-item" placeholder="问题编码" clearable style="width: 130px;" @keyup.enter.native="search" />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="search"
      >{{ $t("table.search") }}</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleAdd">{{ $t('table.add') }}</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-document" @click="handleDownload">
        {{ $t('table.Exportexcel') }}
      </el-button>
    </div>
    <el-table :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)" style="width: 100%;margin-bottom: 20px;" row-key="id" highlight-current-row border>
      <el-table-column prop="code" label="问题编码" sortable />
      <el-table-column prop="name" label="问题分类名称" sortable />
      <el-table-column prop="andon_response_level_id" label="响应级别" sortable>
        <template slot-scope="{row}">
          <span>{{ formatLevel(row.andon_response_level_id) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="andon_response_level_id" label="是否外呼升级" sortable>
        <template slot-scope="{row}">
          <span v-if="row.callType==1">外呼升级</span>
          <span v-if="row.callType==2">外呼不升级</span>
          <span v-if="row.callType==0">不外呼</span>
        </template>
      </el-table-column>
      <el-table-column prop="p_andon_problem_type_id" label="上级分类" sortable :formatter="formatType" />
      <el-table-column :label="$t('table.actions')" align="center">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">{{ $t('table.edit') }}</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top:20px;"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.length"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑':'新增'">
      <el-form :model="andonProblemType" label-width="100px" label-position="left">
        <el-form-item label="问题编码">
          <el-input v-model="andonProblemType.code" placeholder="问题编码" />
        </el-form-item>
        <el-form-item label="问题分类名称">
          <el-input v-model="andonProblemType.name" placeholder="问题分类名称" />
        </el-form-item>
        <el-form-item label="响应级别">
          <el-select v-model="andonProblemType.andon_response_level_id" clearable placeholder="响应级别" class="filter-item" style="width: 130px">
            <el-option v-for="item in levelList" :key="item.id" :label="`${item.level}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否外呼升级">
          <el-select v-model="andonProblemType.callType" clearable placeholder="外呼升级" class="filter-item" style="width: 130px">
            <el-option v-for="item in isSheng" :key="item.val" :label="`${item.text}`" :value="item.val" />
          </el-select>
        </el-form-item>
        <el-form-item label="上级分类">
          <el-select v-model="andonProblemType.p_andon_problem_type_id" clearable placeholder="上级分类" class="filter-item" style="width: 130px">
            <el-option v-for="item in typeList" :key="item.id" :label="`${item.name}`" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">{{ $t('permission.cancel') }}</el-button>
        <el-button type="primary" @click="confirm">{{ $t('permission.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getInfo,
  add,
  update,
  deleteInfo,
  getAllInfo as getTypeAll
} from '@/api/andonProblemType'
import FilenameOption from '@/components/Excel/FilenameOption'
import AutoWidthOption from '@/components/Excel/AutoWidthOption'
import BookTypeOption from '@/components/Excel/BookTypeOption'
import { getAllInfo as getLevelAll } from '@/api/andonProblemLevel'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { deepClone, arraryRemove } from '@/utils'
const andonProblemType = {
  id: 0,
  code: '',
  name: '',
  icon: '',
  andon_response_level_id: 0,
  p_andon_problem_type_id: 0,
  callType: ''
}
export default {
  name: 'AndonProblemType',
  components: { Pagination, FilenameOption, AutoWidthOption, BookTypeOption },
  directives: { waves },
  data() {
    return {
      isSheng: [{
        text: '不外呼',
        val: ''
      }, {
        text: '外呼升级',
        val: 1
      }, {
        text: '外呼不升级',
        val: 2
      }
      ],
      currentPage: 1,
      pagesize: 10,
      downloadLoading: false,
      dialogVisible: false,
      dialogType: 'new',
      total: 0,
      andonProblemType: Object.assign({}, andonProblemType),
      query: {
        pageIndex: 1,
        pageSize: 0
      },
      tableData1: [],
      tableData: [],
      levelList: [{ id: 0, level: '无' }],
      typeList: []
    }
  },
  created() {
    this.getDictionary_option()
  },
  mounted() {
    this.getInfo()
  },
  methods: {
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['问题编码', '问题分类名称', '响应级别', '上级分类']
        const filterVal = ['code', 'name', 'andon_response_level_id', 'icon']
        const tableData = this.tableData
        const data = this.formatJson(filterVal, tableData)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '安灯问题分类',
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getDictionary_option() {
      getLevelAll().then((res) => {
        this.levelList = res.data
      })
      getTypeAll().then((res) => {
        this.typeList = res.data
      })
    },
    getInfo() {
      getInfo(this.query).then((res) => {
        this.tableData = res.data.items
        for (var i = 0; i < this.tableData.length; i++) {
          this.format(this.tableData[i], i)
        }
        this.total = res.data.totalItems
      })
    },
    search() {
      this.query.pageIndex = 1
      this.getInfo()
    },
    handleAdd() {
      this.andonProblemType = Object.assign({}, andonProblemType)
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleUpdate(row) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.andonProblemType = deepClone(row)
      if (!this.andonProblemType.callType || this.andonProblemType.callType == 0) {
        this.andonProblemType.callType = ''
      }
    },
    handleDelete(row, $index) {
      this.$confirm('确认删除?', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await deleteInfo(row.id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          arraryRemove(this.tableData, row)
        })
        .catch((err) => console.error(err))
    },
    async confirm() {
      const isEdit = this.dialogType === 'edit'
      const obj = deepClone(this.andonProblemType)
      if (!obj.callType) {
        obj.callType = 0
      }
      if (isEdit) {
        await update(this.andonProblemType.id, obj)
      } else {
        await add(obj)
      }
      this.getInfo()
      this.dialogVisible = false
      const { code, name } = this.andonProblemType
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        type: 'success'
      })
    },
    formatLevel(id) {
      const rt = this.levelList.find((rt) => rt.id === id)
      return rt ? rt.level : ''
    },
    formatType(row, a, b, index) {
      const rt = this.typeList.find((rt) => rt.id === row.p_andon_problem_type_id)
      return rt ? rt.name : ''
    },
    format(row, index) {
      const rt = this.typeList.find((rt) => { if (rt.id == row.p_andon_problem_type_id) { this.tableData[index].icon = rt.name } })
    }
  }
}
</script>
